{% extends 'new_hire_base.html' %}
{% load i18n %}
{% load humanize %}

{% block actions %}{% endblock %}

{% block content %}
<div class="row justify-content-md-center">
  <div class="col-md-8 col-12">
    <div class="card">
      <div class="card-body" style="position: relative;">
        <h2>{{ object.to_do.name }}</h2>
        {% include '_content.html' with content=object.to_do.content user=request.user %}
        {% if not object.completed %}
        <form method="post" action="{% url 'new_hire:to_do_complete' object.id %}">
          {% csrf_token %}
          <button type="submit" class="btn btn-primary w-100">
            {% translate "I have completed this item!" %}
          </button>
        </form>
        {% else %}
        <b> {% translate "You have already completed this item" %}</p>
        {% endif %}
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
  $(".upload-button").each(function (item) {
    $(this).on('click', function () {
      $(this).parent().find("input").click()
    })
  })
  $(".file-input").each(function (item) {
    $(this).on('change', function (file) {
      // ugly, needs clean up
      const originalButtonText = $(this).parent().find(".upload-button").text()
      const fileField = $(this)
      const fileIdInput = $(this).parent().find(".file-id")
      const newFileName = fileField.val().match(/[^\\/]*$/)[0];
      const fileNameSpan = $(this).parent().find(".file-name");
      const filePreview = $(this).parent().find("img");

      $(this).parent().find(".upload-button").text('{% translate "uploading..." %}')
      $.ajax({
        url: "/api/org/file",
        type: 'post',
        data: {'name': newFileName},
        headers: {'X-CSRFToken': '{{ csrf_token }}'},
        success: function( data ) {
          const fileMetaData = data
          $.ajax({
            type: 'PUT',
            url: data.file.url,
            contentType: 'binary/octet-stream',
            processData: false,
            data: fileField.get()[0].files[0],
            success: function () {
              fileField.parent().find(".upload-button").text(originalButtonText)
              fileIdInput.val(fileMetaData.file.id);
              fileNameSpan.text(newFileName);
              filePreview.attr("src", fileMetaData.file.get_url);
            }
          });
        }
      });
    })
  })
  function getSignedURL (file) {
    return $.ajax({
      url: "/api/org/file",
      type: 'post',
      data: {'name': file.name},
      headers: {'X-CSRFToken': '{{ csrf_token }}'},
    })
  }
  function uploadFile (file, response) {
    return $.ajax({
      type: 'PUT',
      url: response.url,
      contentType: 'binary/octet-stream',
      processData: false,
      data: file
    })
  }
</script>
{% endblock %}
